<?php
namespace app\system\controller;
use app\system\model\AdminRankFunc as Mod;
use yichenthink\utils\ReturnMsg;

class AdminRankFunc extends AdminBase {

	// 根据职务权限id 增加或删除一些功能
	public function update($rank_id, $func = []) {

		$admin = $this->admin;
		$message = '';
		$code = 400;
		$map = [];

		$Mod = new Mod;
		$old = $Mod->where('rank_id', $rank_id)
			->visible(['func_id'])
			->select();
		$oldFunc = [];
		for ($i = 0; $i < count($old); $i++) {
			$oldFunc[] = $old[$i]['func_id'];
		}
		// 匹配差异新数据
		$add = array_diff($func, $oldFunc);
		// 匹配差异删除的数据
		$del = array_diff($oldFunc, $func);
		// 批量添加
		$a = $Mod->add($rank_id, $add);
		// 批量删除
		$d = $Mod->del($rank_id, $del);
		// 返回结果

		$ab = [$a, $d];
		if (null != $a) {
			$message .= '新增' . count($a) . '条数据';
			$code = 200;
		}
		if (null != $d) {
			$message .= ',删除' . $d . '条数据';
			$code = 200;
		}
		ReturnMsg::returnMsg($code, $message, $ab);
	}

	// 根据职务权限id，增加一个或多个功能 $func=可是字符串func_id 也可是数组
	public function add($rank_id, $func = []) {

		if (!is_array($func)) {
			$func = [$func];
		}
		$message = '';
		$code = 400;
		$map = [];

		$Mod = new Mod;
		$old = $Mod->where('rank_id', $rank_id)
			->visible(['func_id'])
			->select();
		$oldFunc = [];
		for ($i = 0; $i < count($old); $i++) {
			$oldFunc[] = $old[$i]['func_id'];
		}
		// 匹配差异新数据
		$add = array_diff($func, $oldFunc);
		// 批量添加
		$a = $Mod->add($rank_id, $add);

		if (null != $a) {
			$message .= '新增' . count($a) . '条数据';
			$code = 200;
		}
		ReturnMsg::returnMsg($code, $message, $a);
	}
	// 根据职务权限id删除一个功能
	public function delete($rank_id = 0, $func_id) {

		$code = 400;
		$map = [];
		$map[] = ['rank_id', '=', $rank_id];
		$map[] = ['func_id', '=', $func_id];
		// print_r($map);
		$Mod = new Mod;
		$old = $Mod->with(['adminRank'])
			->where($map)
			->visible(['func_id', 'func_id'])
			->find();
		if ($old) {
			$code = 200;
			$old->delete();
		}

		ReturnMsg::returnMsg($code, '', $old);
	}

}
